#include "px_animationPlayer.h"
#include "../rendersystem/px_textureatlas.h"

PXAnnimationPlayer* init_animationPlayer( const char * fileName )
{
	PXAnnimationPlayer * ret = (PXAnnimationPlayer *) malloc(sizeof(PXAnnimationPlayer));
	int i;
	ret->animation_data = load_animation(fileName);
	ret->texture = (PXTEXTUREATLAS **) malloc(sizeof(PXTEXTUREATLAS *)*ret->animation_data->image_count);
	for(i  = 0 ; i< ret->animation_data->image_count;i++)
	{
		PXTEXTUREATLAS * temp = (PXTEXTUREATLAS *) malloc(sizeof(PXTEXTUREATLAS));
		init_withfile_png (temp,ret->animation_data->images[i].image_names,10);
		ret->texture[i]=temp;
	}
	ret->asc[0] =0;
	ret->asc[1] =0;
	return ret;
}


void draw_frame(PXAnnimationPlayer* ap,int frameId,int x,int y)
{
	int i ;
	for(i = 0 ;i < ap->animation_data->frames[frameId].module_len;i++)
	{
		int image_id  = ap->animation_data->modules[ap->animation_data->frames[frameId].modules[i].moduleId&0x000000ff].image_id;
		int module_id = ap->animation_data->frames[frameId].modules[i].moduleId&0x000000ff;
		float texCoor [2] ={ap->animation_data->modules[module_id].module_rect.x,ap->animation_data->modules[module_id].module_rect.y};
		setQuad(ap->texture[image_id],
			x+ap->animation_data->frames[frameId].modules[i].x,
			y+ap->animation_data->frames[frameId].modules[i].y,
			ap->animation_data->modules[module_id].module_rect.width,
			ap->animation_data->modules[module_id].module_rect.height,
			texCoor,
			0,
			NULL);
		draw_quads(ap->texture[image_id]);
	}
}
static int _get_delay_count(PXAnnimationPlayer* ap,int actionId,int asi)
{
	return ap->animation_data->actions[actionId].frames[asi].delay;
}
static int _get_seq_count(PXAnnimationPlayer* ap,int actionId)
{
	return ap->animation_data->actions[actionId].frame_len;
}
static void _update_action_squence_controller(PXAnnimationPlayer* ap,int actionId)
{
	if(actionId < 0 || ap ==NULL) {
		return;
	}

	ap->asc[ASC_SQUENCE_DELAY]++;

	if (ap->asc[ASC_SQUENCE_DELAY] < _get_delay_count(ap,actionId, ap->asc[ASC_SEQUENCE_INDEX])){
		return;
	}

	ap->asc[ASC_SQUENCE_DELAY] = 0;
	++ap->asc[ASC_SEQUENCE_INDEX];

	if (ap->asc[ASC_SEQUENCE_INDEX] < _get_seq_count(ap,actionId)){
		return;
	}
	ap->asc[ASC_SEQUENCE_INDEX] = 0;
}
void draw_action(PXAnnimationPlayer* ap,int actionId, int x, int y )
{
	int frameId  = ap->animation_data->actions[actionId].frames[ap->asc[ASC_SEQUENCE_INDEX]].frameId&0x000000ff;
	int updatedX = ap->animation_data->actions[actionId].frames[ap->asc[ASC_SEQUENCE_INDEX]].x+x;
	int updatedY = ap->animation_data->actions[actionId].frames[ap->asc[ASC_SEQUENCE_INDEX]].y+y;
	draw_frame(ap,frameId, updatedX ,updatedY);
	_update_action_squence_controller(ap,actionId);
}
